package com.pingao.mp.modular.common.controller;

import com.pingao.mp.config.MpConfig;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RequestMapping(value = "/common/upload")
@Controller
public class UploadController {

    @Autowired
    private MpConfig mpConfig;

    @PostMapping(value = "/upload")
    @ResponseBody
    public Object upload(@RequestParam(value = "file") MultipartFile file) {
        Map<String, Object> map = new HashMap<>();
        try {
            if (file == null) {
                throw new Exception("上传文件为空");
            } else {
                String oldFileName = file.getOriginalFilename();
                assert oldFileName != null;
                String eName = oldFileName.substring(oldFileName.lastIndexOf("."));
                String newFileName = UUID.randomUUID() + eName;
                Calendar cal = Calendar.getInstance();
                int year = cal.get(Calendar.YEAR);
                int month = cal.get(Calendar.MONTH) + 1;
                int day = cal.get(Calendar.DATE);
                int hour = cal.get(Calendar.HOUR_OF_DAY);
                String p = System.getProperty("user.dir");

                String filePath = "/" + mpConfig.getFilePath() + "/" + +year + "/" + month + "/" + day + "/" + hour;
                File newFile = new File(p + filePath);
                if (!newFile.exists()) {
                    boolean mkdirs = newFile.mkdirs();
                    if (!mkdirs) {
                        throw new Exception("创建目录失败");
                    }
                }
                File fileImg = new File(newFile, newFileName);
                //写入文件
                file.transferTo(fileImg);
                map.put("filePath", filePath + "/" + newFileName);
                map.put("result", "ok");
            }
        } catch (Exception ex) {
            map.put("result", "fail");
            map.put("message", ex.getMessage());
        }
        return map;
    }

    /**
     * 上传道腾讯云服务器（https://cloud.tencent.com/document/product/436/10199）
     */
    @PostMapping(value = "/qcloud")
    @ResponseBody
    public Object Upload(@RequestParam(value = "file") MultipartFile file) {
        Map<String, Object> map = new HashMap<>();
        try {
            if (file == null) {
                throw new Exception("上传文件为空");
            }

            String oldFileName = file.getOriginalFilename();
            assert oldFileName != null;
            String eName = oldFileName.substring(oldFileName.lastIndexOf("."));
            String newFileName = UUID.randomUUID() + eName;
            Calendar cal = Calendar.getInstance();
            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH);
            int day = cal.get(Calendar.DATE);
            // 1 初始化用户身份信息(secretId, secretKey)
            COSCredentials cred = new BasicCOSCredentials(mpConfig.getAccessKey(), mpConfig.getSecretKey());
            // 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
            ClientConfig clientConfig = new ClientConfig(new Region(mpConfig.getBucket()));
            // 3 生成cos客户端
            COSClient cosclient;
            cosclient = new COSClient(cred, clientConfig);
            // bucket的命名规则为{name}-{appid} ，此处填写的存储桶名称必须为此格式
            String bucketName = mpConfig.getBucketName();

            // 简单文件上传, 最大支持 5 GB, 适用于小文件上传, 建议 20 M 以下的文件使用该接口
            // 大文件上传请参照 API 文档高级 API 上传
            try {
                File localFile = File.createTempFile("temp", null);
                file.transferTo(localFile);
                // 指定要上传到 COS 上的路径
                String key = "/" + mpConfig.getQianzui() + "/" + year + "/" + month + "/" + day + "/" + newFileName;
                PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
                cosclient.putObject(putObjectRequest);
                map.put("filePath", mpConfig.getPath() + putObjectRequest.getKey());
                map.put("result", "ok");
            } finally {
                // 关闭客户端(关闭后台线程)
                cosclient.shutdown();
            }
        } catch (Exception ex) {
            map.put("result", "fail");
            map.put("message", ex.getMessage());
        }
        return map;
    }
}
